﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class LpnDA : ILpnDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string DOC_ID = "@DOC_ID";
        private string DOC_TYPE = "@DOC_TYPE";
        private string IPSKey = "@IPSKey";
        private string IS_ACTIVE = "@IS_ACTIVE";
        private string LPN_ID = "@LPN_ID";
        private string PACK_ID = "@PACK_ID";
        private string PUTAWAY_HI = "@PUTAWAY_HI";
        private string PUTAWAY_TI = "@PUTAWAY_TI";
        private string QTY = "@QTY";
        private string SQL_CHECK_LPN_ID_UNIQUE = " SELECT COUNT(1) FROM @_@LPN WHERE LPN_ID = @LPN_ID ";
        private string SQL_DELETE_LPN = " DELETE FROM @_@LPN WHERE LPN_ID = @LPN_ID ";
        private string SQL_DELETE_LPN_BY_DOC_ID = " DELETE FROM @_@LPN WHERE DOC_ID = @DOC_ID AND DOC_TYPE=@DOC_TYPE ";
        private string SQL_INSERT_LPN = " INSERT INTO @_@LPN ( WH_ID, LPN_ID, QTY, STATUS, PACK_ID, PUTAWAY_TI, PUTAWAY_HI, IPSKey, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE,DOC_ID,DOC_TYPE,IS_ACTIVE) VALUES ( @WH_ID, @LPN_ID, @QTY, @STATUS, @PACK_ID, @PUTAWAY_TI, @PUTAWAY_HI, @IPSKey, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE(),@DOC_ID,@DOC_TYPE,@IS_ACTIVE )  ";
        private string SQL_MAX_LPN_BY_LPN_ID = " SELECT MAX(LPN_ID) FROM @_@LPN ";
        private string SQL_NEXT_LPN_BY_DOC_ID = " SELECT COUNT(*) FROM @_@LPN WHERE DOC_ID=@DOC_ID AND DOC_TYPE=@DOC_TYPE ";
        private string SQL_SELECT_ALL_LPN = " SELECT DISTINCT L.ROWID, L.WH_ID, L.LPN_ID, L.QTY, L.STATUS, L.PACK_ID, L.PUTAWAY_TI, L.PUTAWAY_HI, L.IPSKEY, L.TS, L.CREATED_BY, L.CREATED_DATE, L.UPDATED_BY, L.UPDATED_DATE,L.DOC_ID,L.DOC_TYPE,L.IS_ACTIVE, CASE DOC_TYPE  WHEN  'IN' THEN R.EXTERNAL_RECEIPT_ID WHEN 'OT' THEN O.EXTERN_ORDER_ID ELSE '' END AS EXTERN_ID FROM  @_@LPN L LEFT JOIN @_@RECEIPT R ON L.DOC_ID=R.RECEIPT_ID LEFT JOIN @_@ORDERS O ON L.DOC_ID=O.ORDER_ID LEFT JOIN @_@INV_LOT_LOC_LPN ILLL ON L.LPN_ID = ILLL.LPN_ID ";
        private string SQL_UPDATE_LPN = " UPDATE @_@LPN SET WH_ID = @WH_ID, QTY = @QTY, STATUS = @STATUS, PACK_ID = @PACK_ID, PUTAWAY_TI = @PUTAWAY_TI, PUTAWAY_HI = @PUTAWAY_HI, IPSKey = @IPSKey, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE(),DOC_ID=@DOC_ID,DOC_TYPE=@DOC_TYPE,IS_ACTIVE=@IS_ACTIVE WHERE LPN_ID = @LPN_ID  ";
        private string SQL_UPDATE_LPN_QTY = " UPDATE @_@LPN SET QTY = @QTY, UPDATED_BY = @UPDATED_BY ,UPDATED_DATE = GETDATE() WHERE LPN_ID = @LPN_ID  ";
        private string SQL_UPDATE_LPN_STATUS = " UPDATE @_@LPN SET STATUS = @STATUS, UPDATED_BY = @UPDATED_BY ,UPDATED_DATE = GETDATE() WHERE LPN_ID = @LPN_ID  ";
        private string STATUS = "@STATUS";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckLpnIDUnique(string lpnID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", lpnID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_LPN_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckLpnIDUnique(DataBase dataBase, DbTransaction tran, string lpnID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", lpnID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_LPN_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteLpn(List<string> LpnID, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int j = 0; j < LpnID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", LpnID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_LPN.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteLpn(DataBase dataBase, DbTransaction tran, List<string> LpnID, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < LpnID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", LpnID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_LPN.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteLpnByDocID(DataBase dataBase, DbTransaction tran, List<string> DocID, string DocType, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; DocID.Count > i; i++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DOC_ID", DocID[i]), new SqlParameter("@DOC_TYPE", DocType) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_LPN_BY_DOC_ID.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int ExecuteLpnHold(DataBase dataBase, DbTransaction tran, string status, string lpn, string updateBy, string whLoginID)
        {
            int result = 0;
            try
            {
                string sql = string.Empty;
                sql = this.SQL_UPDATE_LPN_STATUS.Replace("@_@", whLoginID);
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATUS", status), new SqlParameter("@UPDATED_BY", updateBy), new SqlParameter("@LPN_ID", lpn) };
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, sql, paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllLpn(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_LPN.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllLpn(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_LPN.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public LpnInfo GetLpnByID(string lpnID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_LPN.Replace("@_@", whLoginID) + " WHERE L.LPN_ID = @LPN_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", lpnID) };
            LpnInfo lpnInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    lpnInfo = new LpnInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["LPN_ID"].ToString(), (reader["QTY"].ToString() != "") ? decimal.Parse(reader["QTY"].ToString()) : 0M, reader["STATUS"].ToString(), reader["PACK_ID"].ToString(), (reader["PUTAWAY_TI"].ToString() != "") ? decimal.Parse(reader["PUTAWAY_TI"].ToString()) : 0M, (reader["PUTAWAY_HI"].ToString() != "") ? decimal.Parse(reader["PUTAWAY_HI"].ToString()) : 0M, reader["IPSKey"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime(), reader["DOC_ID"].ToString(), reader["DOC_TYPE"].ToString(), reader["IS_ACTIVE"].ToString(), reader["EXTERN_ID"].ToString());
                }
            }
            return lpnInfo;
        }

        public LpnInfo GetLpnByID(DataBase dataBase, DbTransaction tran, string lpnID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_LPN.Replace("@_@", whLoginID) + " WHERE L.LPN_ID = @LPN_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@LPN_ID", lpnID) };
            LpnInfo lpnInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                lpnInfo = new LpnInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["LPN_ID"].ToString(), (reader["QTY"].ToString() != "") ? decimal.Parse(reader["QTY"].ToString()) : 0M, reader["STATUS"].ToString(), reader["PACK_ID"].ToString(), (reader["PUTAWAY_TI"].ToString() != "") ? decimal.Parse(reader["PUTAWAY_TI"].ToString()) : 0M, (reader["PUTAWAY_HI"].ToString() != "") ? decimal.Parse(reader["PUTAWAY_HI"].ToString()) : 0M, reader["IPSKey"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime(), reader["DOC_ID"].ToString(), reader["DOC_TYPE"].ToString(), reader["IS_ACTIVE"].ToString(), reader["EXTERN_ID"].ToString());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return lpnInfo;
        }

        public DataSet GetLpnByQueryList(List<string> sqlWhere, LpnQueryEntity lpnQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_LPN.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!lpnQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, lpnQuery.CurrentPage, lpnQuery.PageSize, lpnQuery.SortField, lpnQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public string GetMaxLpnByDocID(string docID, string docType, string whLoginID)
        {
            string sql = this.SQL_MAX_LPN_BY_LPN_ID + " WHERE DOC_ID =@DOC_ID AND DOC_TYPE=@DOC_TYPE";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DOC_ID", docID), new SqlParameter("@DOC_TYPE", docType) };
            return DBHelper.ExecuteScalar(CommandType.Text, sql.Replace("@_@", whLoginID), paras).ToString();
        }

        public string GetMaxLpnByLpnID(string lpnID, string whLoginID)
        {
            string sql = this.SQL_MAX_LPN_BY_LPN_ID + " WHERE LPN_ID LIKE '%" + lpnID + "%'";
            return DBHelper.ExecuteScalar(CommandType.Text, sql.Replace("@_@", whLoginID)).ToString();
        }

        public string GetNextLpnByDocID(string docID, string docType, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@DOC_ID", docID), new SqlParameter("@DOC_TYPE", docType) };
            return DBHelper.ExecuteScalar(CommandType.Text, this.SQL_NEXT_LPN_BY_DOC_ID.Replace("@_@", whLoginID), paras).ToString();
        }

        public int InsertLpn(LpnInfo lpnInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                lpnInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Lpn_Parameters(lpnInfo);
                if (paras != null)
                {
                    result += DBHelper.ExecuteNonQuery(CommandType.Text, this.SQL_INSERT_LPN.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertLpn(DataBase dataBase, DbTransaction tran, LpnInfo lpnInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                lpnInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Lpn_Parameters(lpnInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_LPN.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_Lpn_Parameters(LpnInfo lpnInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.LPN_ID, SqlDbType.VarChar, 20), new SqlParameter(this.QTY, SqlDbType.Decimal, 13), new SqlParameter(this.STATUS, SqlDbType.VarChar, 20), new SqlParameter(this.PACK_ID, SqlDbType.VarChar, 50), new SqlParameter(this.PUTAWAY_TI, SqlDbType.Decimal, 13), new SqlParameter(this.PUTAWAY_HI, SqlDbType.Decimal, 13), new SqlParameter(this.IPSKey, SqlDbType.VarChar, 20), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.DOC_ID, SqlDbType.VarChar, 50), new SqlParameter(this.DOC_TYPE, SqlDbType.VarChar, 30), new SqlParameter(this.IS_ACTIVE, SqlDbType.VarChar, 1) };
            if (!string.IsNullOrEmpty(lpnInfo.WhID))
            {
                paramArray[0].Value = lpnInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = lpnInfo.LpnID;
            paramArray[2].Value = lpnInfo.Qty;
            paramArray[3].Value = lpnInfo.Status;
            paramArray[4].Value = lpnInfo.PackID;
            paramArray[5].Value = lpnInfo.PutawayTi;
            paramArray[6].Value = lpnInfo.PutawayHi;
            if (!string.IsNullOrEmpty(lpnInfo.Ipskey))
            {
                paramArray[7].Value = lpnInfo.Ipskey;
            }
            else
            {
                paramArray[7].Value = DBNull.Value;
            }
            paramArray[8].Value = lpnInfo.CreatedBy;
            paramArray[9].Value = lpnInfo.UpdatedBy;
            paramArray[10].Value = lpnInfo.DocID;
            paramArray[11].Value = lpnInfo.DocType;
            paramArray[12].Value = lpnInfo.IsActive;
            return paramArray;
        }

        public int UpdateLpn(LpnInfo lpnInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                lpnInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Lpn_Parameters(lpnInfo);
                if (paras != null)
                {
                    result += DBHelper.ExecuteNonQuery(CommandType.Text, this.SQL_UPDATE_LPN.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int UpdateLpn(DataBase dataBase, DbTransaction tran, LpnInfo lpnInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                lpnInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Lpn_Parameters(lpnInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_LPN.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int UpdateLpn(DataBase dataBase, DbTransaction tran, LpnInfo lpnInfo, string updateType, string whLoginID)
        {
            int result = 0;
            try
            {
                string sql = string.Empty;
                SqlParameter[] paras = null;
                string CS40001 = updateType;
                if (CS40001 != null)
                {
                    if (!(CS40001 == "Qty"))
                    {
                        if (CS40001 == "Status")
                        {
                            goto Label_0099;
                        }
                    }
                    else
                    {
                        sql = this.SQL_UPDATE_LPN_QTY.Replace("@_@", whLoginID);
                        paras = new SqlParameter[] { new SqlParameter("@QTY", lpnInfo.Qty), new SqlParameter("@UPDATED_BY", lpnInfo.UpdatedBy), new SqlParameter("@LPN_ID", lpnInfo.LpnID) };
                    }
                }
                goto Label_00F5;
            Label_0099:
                sql = this.SQL_UPDATE_LPN_STATUS.Replace("@_@", whLoginID);
                paras = new SqlParameter[] { new SqlParameter("@STATUS", lpnInfo.Status), new SqlParameter("@UPDATED_BY", lpnInfo.UpdatedBy), new SqlParameter("@LPN_ID", lpnInfo.LpnID) };
            Label_00F5:
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, sql, paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

